import * as PIXI from 'pixi.js';
import { ref } from 'vue';

const color = ref('#fff');

/** 使用标注或批注设置成各自的参考线颜色 */
export function setCrosshairColor(v) {
  color.value = v;
}

const Listener = (app, crosshair) => event => {
  // 清空，画横线画竖线
  crosshair.clear();
  crosshair.lineStyle({ width: 1, color: color.value, alpha: .5 });
  crosshair.moveTo(0, event.global.y);
  crosshair.lineTo(app.screen.width, event.global.y);
  crosshair.moveTo(event.global.x, 0);
  crosshair.lineTo(event.global.x, app.screen.height);
  crosshair.closePath();
};

/** @param {import('pixi.js').Application} app */
export function useCrosshair(app) {
  const crosshair = new PIXI.Graphics();
  const listener = Listener(app, crosshair);
  let listenable = true;

  // start 若能添加则添加监听
  // end 移除监听后设为可添加
  function start() {
    if (!listenable) { return; }
    listenable = false;

    crosshair.visible = true;
    listener(app.renderer.events.pointer);
    app.stage.on('pointermove', listener);
  }
  
  function stop() {
    crosshair.visible = false;
    app.stage.off('pointermove', listener);
    listenable = true;
  }

  return { crosshair, start, stop };
}
